package com.hzjiteng.newsbymvp.news.presenter;

import com.hzjiteng.newsbymvp.bean.NewsBean;
import com.hzjiteng.newsbymvp.comment.URLS;
import com.hzjiteng.newsbymvp.news.model.NewsModel;
import com.hzjiteng.newsbymvp.news.model.NewsModelImpl;
import com.hzjiteng.newsbymvp.news.views.NewsView;
import com.hzjiteng.newsbymvp.news.widget.NewsFragment;

import java.util.List;

/**
 * @author Administrator
 * @Email:lijiayan_mail@163.com
 * @created_time 2016/07/29 16:17
 */
public class NewsPrestenerImpl implements NewsPrestener, NewsModelImpl.OnLoadNewsListener {

    private NewsView newsView;

    private NewsModel newsModel;

    public NewsPrestenerImpl(NewsView newsView) {
        this.newsView = newsView;
        newsModel = new NewsModelImpl();
    }

    @Override
    public void loadNews(int type, int page) {
        String url = getUrl(type, page);
        if (page == 0) {
            newsView.showProgress();
        }

        newsModel.loadNews(url, type, this);
    }


    /**
     * 根据类别和页面索引创建url
     *
     * @param type
     * @param pageIndex
     * @return
     */
    private String getUrl(int type, int pageIndex) {
        StringBuffer sb = new StringBuffer();
        switch (type) {
            case NewsFragment.NEWS_TYPE_TOP:
                sb.append(URLS.TOP_URL).append(URLS.TOP_ID);
                break;
            case NewsFragment.NEWS_TYPE_NBA:
                sb.append(URLS.COMMON_URL).append(URLS.NBA_ID);
                break;
            case NewsFragment.NEWS_TYPE_CARS:
                sb.append(URLS.COMMON_URL).append(URLS.CAR_ID);
                break;
            case NewsFragment.NEWS_TYPE_JOKES:
                sb.append(URLS.COMMON_URL).append(URLS.JOKE_ID);
                break;
            default:
                sb.append(URLS.TOP_URL).append(URLS.TOP_ID);
                break;
        }
        sb.append("/").append(pageIndex).append(URLS.END_URL);
        return sb.toString();
    }

    @Override
    public void onSuccess(List<NewsBean> list) {
        newsView.hideProgress();
        newsView.addNews(list);
    }

    @Override
    public void onFailure(Exception e, String msg) {
        newsView.hideProgress();
        newsView.showLoadFailMsg(msg);
        e.printStackTrace();
    }
}
